<template>
  <div class="emplyee-container">
    <div class="left">
      <el-input
        v-model="pageParams.keyword"
        placeholder="请输入内容"
        prefix-icon="el-icon-search"
        style="margin-bottom: 10px"
        @keyup.enter.native="getusers"
        @input="search"
      />
      <el-tree
        ref="treeRef"
        :data="treeData"
        :props="defaultProps"
        default-expand-all
        :expand-on-click-node="false"
        node-key="id"
        highlight-current
        @current-change="handleCheckChange"
      />
    </div>
    <div class="right">
      <div class="r-top">
        <el-button
          size="mini"
          type="primary"
          @click="$router.push('/employee/detail')"
        >添加员工</el-button>
        <el-button size="mini" @click="excelDialog = true">excel导入</el-button>
        <el-button size="mini" @click="exportEmployee">excel导出</el-button>
      </div>
      <div class="r-middle">
        <el-table
          :data="tableData"
          style="width: 100%"
          :default-sort="{ order: 'descending' }"
        >
          <el-table-column label="头像" align="center">
            <template slot-scope="scope">
              <img
                v-if="scope.row.staffPhoto"
                :src="scope.row.staffPhoto"
                style="width: 30px; height: 30px"
                alt=""
              >
              <span
                v-else
                style="
                  display: inline-block;
                  width: 30px;
                  height: 30px;
                  background-color: #04c9be;
                  border-radius: 50%;
                  text-align: center;
                  color: #fff;
                  line-height: 30px;
                "
              >{{ scope.row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="180" />
          <el-table-column prop="mobile" label="手机号" width="180" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              <span>{{
                scope.row.formOfEmployment == 1 ? "正式" : "非正式"
              }}</span>
            </template></el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="$router.push(`/employee/detail/${scope.row.id}`)"
              >查看</el-button>
              <el-button
                size="mini"
                type="text"
                :loading="scope.row.loading"
                @click="editRole(scope.row)"
              >角色</el-button>
              <el-popconfirm
                title="确定要删除这个员工吗?"
                style="margin-left: 10px"
                @onConfirm="handleDelete(scope.row.id)"
              >
                <el-button slot="reference" size="mini" type="text">
                  删除
                </el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="r-bottom">
        <el-pagination
          layout="total, prev, pager, next"
          :page-size="pageParams.pageSize"
          :current-page="pageParams.page"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <ImportExcelCom :visible.sync="excelDialog" @import-success="getusers" />
    <el-dialog
      title="提示"
      :visible.sync="roleDialogVisible"
      @close="cancelRoleDialog"
    >
      <el-checkbox-group v-model="roleList">
        <el-checkbox
          v-for="item in enabledRoleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="assignRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentRequest } from '@/api/department'
import { transformListTotree } from '@/utils'
import {
  getEmployeeRequest,
  exportEmployeeRequest,
  deleteEmployeeRequest,
  getEnabledRoleListRequest,
  getEmployeeDetailRequest,
  assignRolesRequest
} from '@/api/employee'
import _ from 'lodash-es'
import { saveAs } from 'file-saver'
import ImportExcelCom from './components/importExcel.vue'
export default {
  name: 'EmployeeCom',
  components: {
    ImportExcelCom
  },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      pageParams: {
        page: 1,
        pageSize: 10,
        departmentId: 0,
        keyword: ''
      },
      total: 0,
      excelDialog: false,
      // 角色弹窗
      roleDialogVisible: false,
      roleList: [],
      enabledRoleList: [],
      detailId: null
    }
  },
  created() {
    this.getDepartment()
    this.search = _.debounce(this.getusers, 1000)
    this.getEnabledRoleList()
  },
  beforeDestroy() {
    this.search.cancel()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartmentRequest()
      this.treeData = transformListTotree(res.data, 0)
      this.pageParams.departmentId = this.treeData[0].id
      this.$nextTick(() => {
        if (!this.$refs.treeRef) {
          return
        }
        this.$refs.treeRef.setCurrentKey(this.pageParams.departmentId)
      })
      this.getusers()
    },
    handleCheckChange(currentNode) {
      this.pageParams.departmentId = currentNode.id
      this.getusers()
    },
    // 获取角色列表
    async getusers() {
      let res = await getEmployeeRequest(this.pageParams)
      if (res.data.rows.length === 0) {
        this.pageParams.page === 1
          ? (this.pageParams.page = 1)
          : this.pageParams.page--
      }
      res = await getEmployeeRequest(this.pageParams)
      res.data.rows.forEach((item) => {
        item.loading = false
      })
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.getusers()
    },
    search() {
      // this.getusers()
      // 直接在里面写lodash返回的是一个函数,但是并未调用
    },
    // 导出员工列表
    async exportEmployee() {
      if (confirm('确定要导出员工列表吗?')) {
        const res = await exportEmployeeRequest()
        saveAs(res, '员工列表.xlsx')
      }
    },
    // 删除员工
    async handleDelete(id) {
      try {
        await deleteEmployeeRequest(id)
        this.$message.success('删除成功')
        if (this.tableData.length === 1 && this.pageParams.page > 1) {
          this.pageParams.page--
        }
        this.getusers()
      } catch (error) {
        //
      }
    },
    async editRole(row) {
      row.loading = true
      this.detailId = row.id
      if (row.loading) {
        const res = await getEmployeeDetailRequest(row.id)
        this.roleList = res.data.roleIds
        this.roleDialogVisible = true
        // eslint-disable-next-line require-atomic-updates
        row.loading = false
      }
    },
    cancelRoleDialog() {
      this.roleDialogVisible = false
    },
    async getEnabledRoleList() {
      const res = await getEnabledRoleListRequest()
      this.enabledRoleList = res.data
    },
    async assignRoles() {
      const res = await assignRolesRequest({
        id: this.detailId,
        roleIds: this.roleList
      })
      this.$message.success(res.message)
      this.roleDialogVisible = false
      this.detailId = null
      this.roleList = []
    }
  }
}
</script>

<style lang="scss" scoped>
.emplyee-container {
  padding: 20px;
  display: flex;
  .left {
    padding: 20px;
    // background-color: lightcoral;
    flex: 0 1 280px;
  }
  .right {
    padding: 20px;
    // background-color: lightblue;
    flex: 1;
    .r-top {
      text-align: right;
    }
  }
  .r-middle {
    margin: 15px 0;
  }
  .r-bottom {
    text-align: right;
  }
}
</style>
